import { callApi } from "./ai/api.js";

export default defineContentScript({
  matches: ["<all_urls>"],
  main() {
    console.log("AI问答助手已加载");

    // 创建悬浮按钮
    const floatingButton = document.createElement("div");
    floatingButton.innerHTML = `
      <div class="ai-qa-button">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
        </svg>
      </div>
    `;

    // 创建对话框（初始隐藏）
    const chatBox = document.createElement("div");
    chatBox.className = "ai-chatbox";
    chatBox.style.display = "none";
    chatBox.innerHTML = `
      <div class="ai-chatbox-header">
        <h3>AI机务问答助手</h3>
        <button class="ai-close-btn">×</button>
      </div>
      <div class="ai-chatbox-content">
        <div class="ai-welcome">
          <p>欢迎使用AI机务问答助手！</p>
        </div>
        <div class="ai-captured-question" style="display: none;">
          <h4>当前题目：</h4>
          <div class="question-content"></div>
          <button class="ai-explain-btn">解释这道题</button>
        </div>
        <div class="ai-chat-messages"></div>
      </div>
      <div class="ai-chatbox-input">
        <textarea placeholder="输入您的问题..." rows="2"></textarea>
        <button class="ai-send-btn">
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <line x1="22" y1="2" x2="11" y2="13"></line>
            <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
          </svg>
        </button>
      </div>
    `;

    // 添加样式
    const style = document.createElement("style");
    style.textContent = `
      .ai-qa-button {
        position: fixed;
        right: 20px;
        top: 50%;
        transform: translateY(-50%);
        background-color: #4f9bf8;
        color: white;
        width: 48px;
        height: 48px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
        z-index: 10000;
        transition: all 0.3s ease;
      }
      
      .ai-qa-button:hover {
        background-color: #3a8be0;
        transform: translateY(-50%) scale(1.05);
      }
      
      .ai-qa-button svg {
        width: 24px;
        height: 24px;
      }
      
      .ai-chatbox {
        position: fixed;
        right: 20px;
        top: 50%;
        transform: translateY(-50%);
        width: 380px;
        height: 500px;
        background-color: white;
        border-radius: 10px;
        box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3);
        z-index: 10001;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
      }
      
      .ai-chatbox-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 15px;
        background-color: #4f9bf8;
        color: white;
      }
      
      .ai-chatbox-header h3 {
        margin: 0;
        font-size: 16px;
      }
      
      .ai-close-btn {
        background: none;
        border: none;
        color: white;
        font-size: 24px;
        cursor: pointer;
        line-height: 1;
      }
      
      .ai-chatbox-content {
        flex: 1;
        padding: 10px;
        overflow-y: auto;
        background-color: #f5f7f9;
      }
      
      .ai-welcome {
        text-align: center;
        margin: 10px 0;
        color: #666;
      }
      
      .ai-captured-question {
        background-color: #e1f0ff;
        padding: 10px;
        border-radius: 8px;
        margin-bottom: 15px;
      }
      
      .ai-captured-question h4 {
        margin-top: 0;
        color: #2c3e50;
        font-size: 14px;
      }
      
      .question-content {
        white-space: pre-wrap;
        font-size: 14px;
      }
        
   
      .ai-chat-messages {
        display: flex;
        flex-direction: column;
      }
      
      .ai-message {
        max-width: 80%;
        padding: 10px;
        border-radius: 8px;
        margin-bottom: 10px;
        word-break: break-word;
      }
      
      .ai-message.user {
        align-self: flex-end;
        background-color: #dcf8c6;
      }
      
      .ai-message.assistant {
        align-self: flex-start;
        background-color: white;
      }
      
      /* 添加加载动画相关样式 */
      .ai-message.assistant.loading {
        padding-bottom: 8px;
        animation: ai-message-pulse 2s infinite ease-in-out;
      }
      
      @keyframes ai-message-pulse {
        0% {
          box-shadow: 0 0 0 rgba(79, 155, 248, 0);
        }
        50% {
          box-shadow: 0 0 10px rgba(79, 155, 248, 0.3);
        }
        100% {
          box-shadow: 0 0 0 rgba(79, 155, 248, 0);
        }
      }
      
      .ai-loading-indicator {
        display: flex;
        align-items: center;
      }
      
      .ai-loading-dot {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background-color: #4f9bf8;
        margin-right: 4px;
        animation: ai-loading-bounce 1.4s infinite ease-in-out both;
      }
      
      .ai-loading-dot:nth-child(1) {
        animation-delay: -0.32s;
      }
      
      .ai-loading-dot:nth-child(2) {
        animation-delay: -0.16s;
      }
      
      @keyframes ai-loading-bounce {
        0%, 80%, 100% {
          transform: scale(0);
        }
        40% {
          transform: scale(1);
        }
      }
      
      .ai-loading-text {
        font-size: 14px;
        color: #666;
        margin-left: 4px;
      }
      
      .ai-chatbox-input {
        display: flex;
        padding: 10px 15px;
        border-top: 1px solid #eee;
        background-color: white;
      }
      
      .ai-chatbox-input textarea {
        flex: 1;
        padding: 8px 10px;
        border: 1px solid #ddd;
        border-radius: 4px;
        resize: none;
        font-family: inherit;
        font-size: 14px;
      }
      
      .ai-chatbox-input textarea:focus {
        outline: none;
        border-color: #4f9bf8;
      }
      
      .ai-send-btn {
        width: 36px;
        height: 36px;
        background-color: #4f9bf8;
        color: white;
        border: none;
        border-radius: 4px;
        margin-left: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
      }
      
      .ai-send-btn:hover {
        background-color: #3a8be0;
      }
      
      .ai-explain-btn {
        background-color: #4f9bf8;
        color: white;
        border: none;
        border-radius: 4px;
        padding: 6px 12px;
        margin-top: 10px;
        cursor: pointer;
        font-size: 14px;
        transition: background-color 0.2s;
      }
      
      .ai-explain-btn:hover {
        background-color: #3a8be0;
      }
    `;

    document.head.appendChild(style);
    document.body.appendChild(floatingButton);
    document.body.appendChild(chatBox);

    // 当前捕获的题目
    let capturedQuestion = null;

    // 事件处理
    const closeButton = chatBox.querySelector(".ai-close-btn");
    const sendButton = chatBox.querySelector(".ai-send-btn");
    const explainButton = chatBox.querySelector(".ai-explain-btn");
    const textarea = chatBox.querySelector("textarea");
    const chatMessages = chatBox.querySelector(".ai-chat-messages");

    // 存储当前的observer
    let currentObserver = null;

    // 打开关闭对话框
    floatingButton.addEventListener("click", () => {
      floatingButton.style.display = "none";
      chatBox.style.display = "flex";
      findQuestion();

      // 启动MutationObserver监听页面变化
      currentObserver = setupMutationObserver();
    });

    closeButton.addEventListener("click", () => {
      chatBox.style.display = "none";
      floatingButton.style.display = "flex";

      // 关闭监听器
      if (currentObserver) {
        currentObserver.disconnect();
        currentObserver = null;
        console.log("已停止页面监听");
      }
    });

    // 发送问题
    sendButton.addEventListener("click", () => {
      sendQuestion();
    });

    // 支持回车发送
    textarea.addEventListener("keypress", (e) => {
      if (e.key === "Enter" && !e.shiftKey) {
        e.preventDefault();
        sendQuestion();
      }
    });

    // 解释按钮点击事件
    explainButton.addEventListener("click", () => {
      // 获取完整的题目内容，包括标题和内容
      const questionContainer = document.querySelector(".ai-captured-question");
      const questionTitle = questionContainer.querySelector("h4").textContent;
      const questionContent =
        document.querySelector(".question-content").innerHTML;

      // 组合完整题目信息
      const fullQuestionContext = `${questionTitle}\n${questionContent}`;

      console.log("完整题目内容:", fullQuestionContext);

      // 构建"解释这道题"的请求
      const questionText = "请详细解释这道题目，分析其含义和可能的答案";

      // 不在对话框中添加消息，直接调用API
      sendExplainRequestSilently(fullQuestionContext, questionText);
    });

    // 设置MutationObserver监听页面变化
    function setupMutationObserver() {
      // 检查是否在机务在线网站
      let type = null;
      let errorMessage = null;

      if (!document.title.includes("机务在线")) {
        errorMessage = "当前不是机务在线网站，请访问 https://www.airacm.com/";
      } else if (window.location.href.includes("a=reviews&q=tagview")) {
        type = "review";
      } else if (window.location.href.includes("a=inorder")) {
        type = "inorder";
      } else if (window.location.href.includes("a=collect")) {
        type = "collect";
      } else if (window.location.href.includes("a=practice")) {
        type = "practice";
      } else if (window.location.href.includes("a=error")) {
        type = "error";
      } else {
        errorMessage = "请导航至练习、考试、错题集或收藏题目页面";
      }

      // 如果不在正确的页面，显示提示信息并返回
      if (errorMessage) {
        // 隐藏问题区域
        const questionContainer = document.querySelector(
          ".ai-captured-question"
        );
        if (questionContainer) {
          questionContainer.style.display = "none";
        }

        // 显示错误消息
        const messages = document.querySelector(".ai-chat-messages");
        if (messages) {
          // 移除之前的错误消息
          const errorMessages = messages.querySelectorAll(".ai-message.error");
          errorMessages.forEach((msg) => msg.remove());

          // 添加新的错误消息
          const errorDiv = document.createElement("div");
          errorDiv.className = "ai-message assistant error";
          errorDiv.textContent = errorMessage;
          messages.appendChild(errorDiv);
        }
        return null;
      }

      // 创建防抖函数
      let debounceTimer = null;
      const debouncedFindQuestion = () => {
        if (debounceTimer) {
          clearTimeout(debounceTimer);
        }
        debounceTimer = setTimeout(() => {
          requestAnimationFrame(() => {
            findQuestionForType(type);
          });
        }, 100); // 100ms的防抖时间
      };

      // 创建MutationObserver实例
      let observer = new MutationObserver((mutations) => {
        const hasRelevantChanges = mutations.some(
          (mutation) =>
            mutation.type === "childList" || mutation.type === "attributes"
        );

        if (hasRelevantChanges) {
          debouncedFindQuestion();
        }
      });

      // 根据类型定义要观察的目标元素
      let targetNode = null;

      if (type === "review" || type === "error" || type === "collect") {
        targetNode = document.querySelector(".p10");
      } else if (type === "inorder") {
        targetNode = document.querySelector(`#ui-exam-show-box`);
      } else if (type === "practice") {
        targetNode = document.querySelector("#ui-exam-examone2");
      }

      console.log("targetNode", targetNode);

      // 配置观察选项
      const config = {
        attributes: true,
        childList: true,
        subtree: true,
      };

      // 如果找到目标元素，则开始观察
      if (targetNode) {
        observer.observe(targetNode, config);
        console.log(`开始监听页面变化，类型: ${type}`);
        return observer; // 返回observer以便后续停止监听
      }

      // 如果没有找到目标元素，显示错误消息
      errorMessage = "未找到题目区域，请确认是否在正确的页面";
      const messages = document.querySelector(".ai-chat-messages");
      if (messages) {
        // 移除之前的错误消息
        const errorMessages = messages.querySelectorAll(".ai-message.error");
        errorMessages.forEach((msg) => msg.remove());

        // 添加新的错误消息
        const errorDiv = document.createElement("div");
        errorDiv.className = "ai-message assistant error";
        errorDiv.textContent = errorMessage;
        messages.appendChild(errorDiv);
      }

      return null;
    }

    // 查找并初始化当前可见的元素
    function findVisibleExamElement(targetSelectors) {
      let found = null;

      targetSelectors.forEach((selector) => {
        const elements = document.querySelectorAll(selector);

        elements.forEach((element) => {
          const style = window.getComputedStyle(element);
          if (style.display !== "none") {
            found = element;
          }
        });
      });

      return found;
    }

    /**
     * 寻找页面上display不为nong的题目和选项
     */
    function findQuestion() {
      // 检查是否在机务在线网站
      // const isAiracmSite =
      //   document.title.includes("机务在线") &&
      //   (window.location.href.includes("a=reviews&q=tagview") ||
      //     window.location.href.includes("a=inorder") ||
      //     window.location.href.includes("a=collect") ||
      //     window.location.href.includes("a=practice") ||
      //     window.location.href.includes("a=error"));

      let type = null;
      if (document.title.includes("机务在线")) {
        if (window.location.href.includes("a=reviews&q=tagview")) {
          type = "review";
        } else if (window.location.href.includes("a=inorder")) {
          type = "inorder";
        } else if (window.location.href.includes("a=collect")) {
          type = "collect";
        } else if (window.location.href.includes("a=practice")) {
          type = "practice";
        } else if (window.location.href.includes("a=error")) {
          type = "error";
        } else {
          return;
        }
      } else {
        return;
      }

      findQuestionForType(type);
    }

    let currentVisibleElement = null;

    /**
     * 根据网页的类型寻找试题
     */
    function findQuestionForType(type) {
      console.log("type", type);
      
      // 清空对话框
      const chatMessages = document.querySelector(".ai-chat-messages");
      if (chatMessages) {
        chatMessages.innerHTML = "";
      }
      
      const idInput = document.querySelector("#ui-exam-jump-page");
      const pageNumber = idInput ? parseInt(idInput.value) : null;

      let title = "";
      let options = new Array();
      let errorMessage = null;

      try {
        if (type == "review") {
          const targetSelectors = [".ui-exam-options"];
          // 当前可见元素
          currentVisibleElement = findVisibleExamElement(targetSelectors);
          if (!currentVisibleElement) {
            errorMessage = "未能找到当前题目，请等待页面加载完成...";
            throw new Error(errorMessage);
          }
          console.log(`找到可见的考试元素:`, currentVisibleElement);

          const titleElement = currentVisibleElement.querySelector(".b");
          if (!titleElement) {
            errorMessage = "未能找到题目内容，请确认页面已正确加载";
            throw new Error(errorMessage);
          }
          title = titleElement.innerHTML;

          const items = currentVisibleElement.querySelectorAll(".cc");
          if (items.length === 0) {
            errorMessage = "未能找到选项内容，请确认页面已正确加载";
            throw new Error(errorMessage);
          }

          for (let index = 0; index < items.length; index++) {
            const element = items[index].querySelectorAll(".z");
            let selectItem = "";
            for (let i = 0; i < element.length; i++) {
              const item = element[i];
              selectItem += item.innerHTML;
            }
            options.push(selectItem);
          }
        } else if (type == "inorder" || type == "practice") {
          currentVisibleElement = document.querySelector(
            `#ui-exam-show-${pageNumber}`
          );
          if (!currentVisibleElement) {
            errorMessage = "未能找到当前题目，请等待页面加载完成...";
            throw new Error(errorMessage);
          }

          const titleElement =
            currentVisibleElement.querySelector(".ui-exam-title");
          if (!titleElement) {
            errorMessage = "未能找到题目内容，请确认页面已正确加载";
            throw new Error(errorMessage);
          }
          title = titleElement.innerHTML;

          if (type == "practice") {
            const items = currentVisibleElement.querySelectorAll("label");
            if (items.length === 0) {
              errorMessage = "未能找到选项内容，请确认页面已正确加载";
              throw new Error(errorMessage);
            }

            for (let index = 0; index < items.length; index++) {
              const element = items[index];
              const item = element.querySelector(".z");
              if (item) {
                const letterIndex = index;
                const letter = String.fromCharCode(65 + letterIndex);
                let option = `<div class="z" style="width: 100%;">${letter}. ${item.innerHTML}</div>`;
                options.push(option);
              }
            }
          } else {
            const items = currentVisibleElement.querySelector(".ui-exam-item");
            if (!items) {
              errorMessage = "未能找到选项内容，请确认页面已正确加载";
              throw new Error(errorMessage);
            }
            const lis = items.querySelectorAll("li");
            for (let index = 0; index < lis.length; index++) {
              const element = lis[index];
              const label = element.querySelector("label");
              if (label) {
                options.push(label.innerHTML);
              }
            }
          }
        } else if (type == "error" || type == "collect") {
          const targetSelectors = [".ui-exam-options"];
          currentVisibleElement = findVisibleExamElement(targetSelectors);
          if (!currentVisibleElement) {
            errorMessage = "未能找到当前题目，请等待页面加载完成...";
            throw new Error(errorMessage);
          }

          const titleElement = currentVisibleElement.querySelector(".b");
          if (!titleElement) {
            errorMessage = "未能找到题目内容，请确认页面已正确加载";
            throw new Error(errorMessage);
          }
          title = titleElement.innerHTML;

          const items = currentVisibleElement.querySelectorAll(".cl");
          if (items.length === 0) {
            errorMessage = "未能找到选项内容，请确认页面已正确加载";
            throw new Error(errorMessage);
          }

          for (let index = 0; index < items.length; index++) {
            const element = items[index].querySelectorAll(".z");
            let selectItem = "";
            for (let i = 0; i < element.length; i++) {
              const item = element[i];
              selectItem += item.innerHTML;
            }
            options.push(selectItem);
          }
        }

        // 如果成功获取到题目，构建HTML内容
        let htmlContent = `<p>${title}</p><ul>`;
        options.forEach((option) => {
          htmlContent += `<li>${option}</li>`;
        });
        htmlContent += `</ul>`;

        // 获取 .question-content 元素
        const questionContentElement =
          document.querySelector(".question-content");
        if (!questionContentElement) {
          errorMessage = "未能找到题目显示区域，请刷新页面重试";
          throw new Error(errorMessage);
        }

        // 插入 HTML 内容
        questionContentElement.innerHTML = htmlContent;

        // 显示问题区域，隐藏错误提示
        const questionContainer = document.querySelector(
          ".ai-captured-question"
        );
        if (questionContainer) {
          questionContainer.style.display = "block";
        }

        // 清除之前的错误提示消息
        const messages = document.querySelector(".ai-chat-messages");
        if (messages) {
          const errorMessages = messages.querySelectorAll(".ai-message.error");
          errorMessages.forEach((msg) => msg.remove());
        }
      } catch (error) {
        console.error("获取题目失败:", error);

        // 隐藏问题区域
        const questionContainer = document.querySelector(
          ".ai-captured-question"
        );
        if (questionContainer) {
          questionContainer.style.display = "none";
        }

        // 显示错误消息
        const messages = document.querySelector(".ai-chat-messages");
        if (messages) {
          // 移除之前的错误消息
          const errorMessages = messages.querySelectorAll(".ai-message.error");
          errorMessages.forEach((msg) => msg.remove());

          // 添加新的错误消息
          const errorDiv = document.createElement("div");
          errorDiv.className = "ai-message assistant error";
          errorDiv.textContent =
            errorMessage || "获取题目时发生错误，请刷新页面重试";
          messages.appendChild(errorDiv);
        }
      }
    }

    let questionLength = 0;

    // 查找当前可见的题目标题文本
    function findVisibleQuestionTitle() {
      const questionTitles = document.querySelectorAll(".ui-exam-title");
      if (
        questionTitles.length != 1 &&
        questionTitles.length > questionLength
      ) {
        questionLength = questionTitles.length;
        return true;
      } else {
        return false;
      }
    }

    // Initialize a flag to track if the update message has been shown
    let updateMessageShown = false;

    // 捕获当前问题的函数
    function captureCurrentQuestion() {
      // 检查是否在机务在线网站
      const isAiracmSite =
        window.location.href.includes("airacm.com") ||
        document.title.includes("机务在线");

      if (isAiracmSite) {
        console.log(window.location.href);

        if (window.location.href.includes("a=inorder")) {
          // 专门查找练习模式题目内容

          // 专门查找考试题目内容
          const questionTitles = document.querySelectorAll(".ui-exam-title");
          const questionItems = document.querySelectorAll(".ui-exam-item");

          if (questionTitles.length > 0) {
            // 获取当前可见的题目
            const questionTitle = questionTitles[questionTitles.length - 1];
            const questionContent = questionItems[questionItems.length - 1];

            // 向背景脚本发送捕获内容（可选）
            // sendToBackground({
            //   type: "capturedContent",
            //   data: capturedQuestion,
            //   url: window.location.href,
            //   title: document.title,
            // });

            // 提取问题
            const question = questionTitle.innerHTML;

            // 提取选项
            const options = Array.from(
              questionItems[questionItems.length - 1].querySelectorAll("label")
            ).map((label) => label.textContent.trim());

            // 构建 HTML 内容
            let htmlContent = `<p>${question}</p><ul>`;
            options.forEach((option) => {
              htmlContent += `<li>${option}</li>`;
            });
            htmlContent += `</ul>`;

            // 获取 .question-content 元素
            const questionContentElement =
              document.querySelector(".question-content");

            // 插入 HTML 内容
            questionContentElement.innerHTML = htmlContent;

            // 显示问题区域
            const questionContainer = document.querySelector(
              ".ai-captured-question"
            );
            questionContainer.style.display = "block";

            // 清空对话历史记录
            const chatMessages = document.querySelector(".ai-chat-messages");
            chatMessages.innerHTML = "";

            // 滚动到顶部
            const content = chatBox.querySelector(".ai-chatbox-content");
            content.scrollTop = 0;

            // 添加欢迎消息，告知用户新题目已捕获
            addAIMessage("我已捕获新的题目，您可以针对这个题目向我提问。");
          }
        } else if (window.location.href.includes("a=reviews&q=tagview")) {
          // 专门查找考试题目内容
          // todo 后续需要在这个页面中获取考试模式的相关题目
          //选择class等于ui-exam-options且display不等于none的元素
          const questionTitles = document.querySelectorAll(".ui-exam-options");
          console.log(questionTitles);
        } else {
          addAIMessage("该模式只在练习页面和回顾试卷的错题标记模式有效。");
        }
      } else {
        // 不是目标网站
        addAIMessage(
          "当前页面不是机务在线网站，请访问 https://www.airacm.com/ 并导航到学习页面。"
        );
      }
    }

    // 替换现有的cryptoUtils对象
    const cryptoUtils = {
      // 简单的XOR混淆函数
      _xorEncodeDecode(str, key) {
        // 确保key是字符串
        key = String(key || browser.runtime.id || 'default-key');
        
        // 生成一个固定的密钥序列
        let keyChars = [];
        for (let i = 0; i < 256; i++) {
          keyChars[i] = key.charCodeAt(i % key.length);
        }
        
        // XOR操作
        let result = "";
        for (let i = 0; i < str.length; i++) {
          const charCode = str.charCodeAt(i) ^ keyChars[i % 256];
          result += String.fromCharCode(charCode);
        }
        
        return result;
      },
      
      // Base64解码并解混淆
      async decryptApiKey(encodedApiKey) {
        if (!encodedApiKey) return '';
        
        try {
          console.log('开始解混淆API密钥...');
          
          // 首先进行Base64解码
          const decoded = atob(encodedApiKey);
          
          // 然后进行XOR解混淆
          const result = this._xorEncodeDecode(decoded, browser.runtime.id);
          
          console.log('API密钥解混淆成功, 长度:', result.length);
          if (result.length > 0) {
            // 打印前几个字符用于调试
            console.log('解混淆密钥前缀:', result.substring(0, 5) + '...');
          }
          
          return result;
        } catch (error) {
          console.error('API密钥解混淆失败:', error);
          console.log('尝试直接返回原始密钥...');
          return encodedApiKey; // 失败时返回原始值
        }
      }
    };

    // 修改sendQuestion函数中的解密部分
    async function sendQuestion() {
      // 如果正在生成，则不允许发送新请求
      if (isGenerating) return;

      const questionText = textarea.value.trim();
      if (!questionText) return;

      // 添加用户消息到聊天框
      addUserMessage(questionText);

      // 清空输入框
      textarea.value = "";

      // 获取用户设置的API参数
      const options = await browser.storage.sync.get([
        "apiUrl",
        "providerApiKeys",
        "apiVersion",
        "provider",
      ]);

      const apiUrl = options.apiUrl;
      const encryptedProviderApiKeys = options.providerApiKeys;
      const apiVersion = options.apiVersion;
      const provider = options.provider;

      // 检查是否设置了API参数
      if (!apiUrl || !encryptedProviderApiKeys || !apiVersion) {
        addAIMessage("API参数未设置，请先在设置中配置API信息。");
        return;
      }

      // 解密当前提供商的API密钥
      let decryptedApiKey = '';
      try {
        if (encryptedProviderApiKeys && provider && encryptedProviderApiKeys[provider]) {
          console.log(`正在解混淆 ${provider} 的API密钥...`);
          decryptedApiKey = await cryptoUtils.decryptApiKey(encryptedProviderApiKeys[provider]);
          console.log(`密钥解混淆完成，密钥长度: ${decryptedApiKey.length}`);
        } else {
          console.warn("没有找到当前提供商的API密钥");
        }
      } catch (error) {
        console.error("处理API密钥失败:", error);
        addAIMessage("处理API密钥失败，请重新配置API密钥。");
        return;
      }

      // 如果解密后的密钥看起来不合理（太短或包含奇怪字符），尝试使用原始值
      if (!decryptedApiKey || decryptedApiKey.length < 10 || /[^\x20-\x7E]/.test(decryptedApiKey)) {
        console.warn("解混淆后的API密钥不合理，尝试使用原始值...");
        decryptedApiKey = encryptedProviderApiKeys[provider];
        
        // 尝试Base64解码
        try {
          decryptedApiKey = atob(decryptedApiKey);
          console.log("使用Base64解码的原始值");
        } catch (e) {
          console.log("原始值不是有效的Base64，直接使用原始值");
        }
      }

      // 创建AI消息占位符用于流式输出
      const messageElement = addAIMessageElement("");

      // 标记为正在生成
      isGenerating = true;
      const inputArea = document.querySelector(".ai-chatbox-input");
      inputArea.classList.add("ai-generating");

      // 使用流式输出回调
      const onChunk = (chunk) => {
        // 第一个chunk时，移除加载动画
        if (messageElement.classList.contains("loading") && chunk) {
          // 清除文字轮换计时器
          if (messageElement.dataset.intervalId) {
            clearInterval(parseInt(messageElement.dataset.intervalId));
            delete messageElement.dataset.intervalId;
          }

          messageElement.classList.remove("loading");
          messageElement.innerHTML = "";
          messageElement.textContent = chunk;
        } else {
          messageElement.textContent += chunk;
        }
        scrollToBottom();
      };

      try {
        // 获取完整的题目内容，包括标题和内容
        const questionContainer = document.querySelector(
          ".ai-captured-question"
        );
        const questionTitle = questionContainer.querySelector("h4").textContent;
        const questionContent =
          document.querySelector(".question-content").innerHTML;

        // 组合完整题目信息
        const fullQuestionContext = `${questionTitle}\n${questionContent}`;

        // 生成请求ID
        currentRequestId = Date.now().toString();

        // 调用API获取回答，传递完整题目上下文和请求ID，使用解密后的API密钥
        await callApi(
          apiUrl,
          decryptedApiKey,
          apiVersion,
          provider,
          questionText,
          onChunk,
          fullQuestionContext,
          currentRequestId
        ).then((response) => {
          console.log("response", response);

          if (!response) {
            // 如果仍然有loading类，说明没有返回任何内容，显示错误
            if (messageElement.classList.contains("loading")) {
              // 清除文字轮换计时器
              if (messageElement.dataset.intervalId) {
                clearInterval(parseInt(messageElement.dataset.intervalId));
                delete messageElement.dataset.intervalId;
              }

              messageElement.classList.remove("loading");
              messageElement.innerHTML = "API调用失败，请稍后重试。";
            } else {
              messageElement.textContent = "API调用失败，请稍后重试。";
            }
          }

          // 完成生成，更新UI状态
          isGenerating = false;
          inputArea.classList.remove("ai-generating");
          currentRequestId = null;
        });
      } catch (error) {
        console.error("发送请求时出错:", error);
        messageElement.textContent = `请求失败: ${error.message}`;

        // 出错时也要更新UI状态
        isGenerating = false;
        inputArea.classList.remove("ai-generating");
        currentRequestId = null;
      }
    }

    // 创建一个不在对话框显示用户消息的解释请求函数
    async function sendExplainRequestSilently(
      fullQuestionContext,
      questionText
    ) {
      // 如果正在生成，则不允许发送新请求
      if (isGenerating) return;

      // 获取用户设置的API参数
      const options = await browser.storage.sync.get([
        "apiUrl",
        "providerApiKeys",
        "apiVersion",
        "provider",
      ]);
      const apiUrl = options.apiUrl;
      const encryptedProviderApiKeys = options.providerApiKeys;
      const apiVersion = options.apiVersion;
      const provider = options.provider;

      // 检查是否设置了API参数
      if (!apiUrl || !encryptedProviderApiKeys || !apiVersion) {
        addAIMessage("API参数未设置，请先在设置中配置API信息。");
        return;
      }

      // 解密当前提供商的API密钥
      let decryptedApiKey = '';
      try {
        if (encryptedProviderApiKeys && provider && encryptedProviderApiKeys[provider]) {
          console.log(`正在解混淆 ${provider} 的API密钥...`);
          decryptedApiKey = await cryptoUtils.decryptApiKey(encryptedProviderApiKeys[provider]);
          console.log(`密钥解混淆完成，密钥长度: ${decryptedApiKey.length}`);
        } else {
          console.warn("没有找到当前提供商的API密钥");
        }
      } catch (error) {
        console.error("处理API密钥失败:", error);
        addAIMessage("处理API密钥失败，请重新配置API密钥。");
        return;
      }

      // 如果解密后的密钥看起来不合理（太短或包含奇怪字符），尝试使用原始值
      if (!decryptedApiKey || decryptedApiKey.length < 10 || /[^\x20-\x7E]/.test(decryptedApiKey)) {
        console.warn("解混淆后的API密钥不合理，尝试使用原始值...");
        decryptedApiKey = encryptedProviderApiKeys[provider];
        
        // 尝试Base64解码
        try {
          decryptedApiKey = atob(decryptedApiKey);
          console.log("使用Base64解码的原始值");
        } catch (e) {
          console.log("原始值不是有效的Base64，直接使用原始值");
        }
      }

      // 创建空的AI消息占位符用于流式输出
      const messageElement = addAIMessageElement("");

      // 标记为正在生成
      isGenerating = true;
      const inputArea = document.querySelector(".ai-chatbox-input");
      inputArea.classList.add("ai-generating");

      // 使用流式输出回调
      const onChunk = (chunk) => {
        // 第一个chunk时，移除加载动画
        if (messageElement.classList.contains("loading") && chunk) {
          // 清除文字轮换计时器
          if (messageElement.dataset.intervalId) {
            clearInterval(parseInt(messageElement.dataset.intervalId));
            delete messageElement.dataset.intervalId;
          }

          messageElement.classList.remove("loading");
          messageElement.innerHTML = "";
          messageElement.textContent = chunk;
        } else {
          messageElement.textContent += chunk;
        }
        scrollToBottom();
      };

      // 生成请求ID
      currentRequestId = Date.now().toString();

      // 调用API获取回答，传递完整题目上下文和请求ID
      try {
        const response = await callApi(
          apiUrl,
          decryptedApiKey,
          apiVersion,
          provider,
          questionText,
          onChunk,
          fullQuestionContext,
          currentRequestId
        );

        if (!response) {
          // 如果仍然有loading类，说明没有返回任何内容，显示错误
          if (messageElement.classList.contains("loading")) {
            // 清除文字轮换计时器
            if (messageElement.dataset.intervalId) {
              clearInterval(parseInt(messageElement.dataset.intervalId));
              delete messageElement.dataset.intervalId;
            }

            messageElement.classList.remove("loading");
            messageElement.innerHTML = "API调用失败，请稍后重试。";
          } else {
            messageElement.textContent = "API调用失败，请稍后重试。";
          }
        }
      } catch (error) {
        console.error("发送请求时出错:", error);
        // 如果仍然有loading类，说明没有返回任何内容，显示错误
        if (messageElement.classList.contains("loading")) {
          // 清除文字轮换计时器
          if (messageElement.dataset.intervalId) {
            clearInterval(parseInt(messageElement.dataset.intervalId));
            delete messageElement.dataset.intervalId;
          }

          messageElement.classList.remove("loading");
          messageElement.innerHTML = `请求失败: ${error.message}`;
        } else {
          messageElement.textContent = `请求失败: ${error.message}`;
        }
      } finally {
        // 完成生成，更新UI状态
        isGenerating = false;
        inputArea.classList.remove("ai-generating");
        currentRequestId = null;
      }
    }

    // 添加用户消息
    function addUserMessage(text) {
      const message = document.createElement("div");
      message.className = "ai-message user";
      message.textContent = text;
      chatMessages.appendChild(message);
      scrollToBottom();
    }

    // 添加AI消息 - returns the message
    function addAIMessageElement(text) {
      const message = document.createElement("div");
      message.className = "ai-message assistant";

      // 如果是空文本，添加加载指示器
      if (text === "") {
        message.classList.add("loading");

        // 创建加载指示器容器
        const loadingIndicator = document.createElement("div");
        loadingIndicator.className = "ai-loading-indicator";

        // 添加三个点
        for (let i = 0; i < 3; i++) {
          const dot = document.createElement("div");
          dot.className = "ai-loading-dot";
          loadingIndicator.appendChild(dot);
        }

        // 创建文字提示容器
        const loadingText = document.createElement("span");
        loadingText.className = "ai-loading-text";
        loadingText.textContent = "思考中";
        loadingIndicator.appendChild(loadingText);

        message.appendChild(loadingIndicator);

        // 设置文字轮换
        const loadingTexts = [
          "思考中",
          "正在分析问题",
          "在知识库中查找",
          "整理相关信息",
          "生成回答中",
          "请稍等片刻",
        ];

        let textIndex = 0;
        // 每2.5秒切换一次提示文字
        const textInterval = setInterval(() => {
          textIndex = (textIndex + 1) % loadingTexts.length;
          loadingText.textContent = loadingTexts[textIndex];
        }, 2500);

        // 存储interval ID，以便在收到响应时清除
        message.dataset.intervalId = textInterval;
      } else {
        message.textContent = text;
      }

      chatMessages.appendChild(message);
      scrollToBottom();
      return message;
    }

    // 添加AI消息 - 保持兼容旧代码
    function addAIMessage(text) {
      addAIMessageElement(text);
    }

    // 滚动到底部
    function scrollToBottom() {
      const content = chatBox.querySelector(".ai-chatbox-content");
      content.scrollTop = content.scrollHeight;
    }

    // // 监听来自popup或background的消息
    // browser.runtime.onMessage.addListener((message) => {
    //   if (message.action === "captureDom") {
    //     captureCurrentQuestion();
    //     return Promise.resolve({ success: true });
    //   }
    // });

    // // 发送数据到background
    // function sendToBackground(data) {
    //   browser.runtime
    //     .sendMessage(data)
    //     .catch((err) => console.error("发送数据到background时出错:", err));
    // }

    // 修改停止按钮的实现
    function setupStopButton() {
      // 检查是否已经存在停止按钮
      if (document.querySelector(".ai-stop-btn")) return;

      // 创建停止按钮
      const stopButton = document.createElement("button");
      stopButton.className = "ai-stop-btn";
      stopButton.innerHTML = `
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
        </svg>
      `;
      stopButton.title = "停止生成";

      // 添加到输入框区域
      const inputArea = document.querySelector(".ai-chatbox-input");
      const sendButton = document.querySelector(".ai-send-btn");
      inputArea.insertBefore(stopButton, sendButton);

      // 添加单独的样式标签
      const style = document.createElement("style");
      style.textContent = `
        .ai-stop-btn {
          width: 36px;
          height: 36px;
          background-color: #e74c3c;
          color: white;
          border: none;
          border-radius: 4px;
          margin-left: 8px;
          display: none; /* 默认隐藏 */
          align-items: center;
          justify-content: center;
          cursor: pointer;
        }
        
        .ai-stop-btn:hover {
          background-color: #c0392b;
        }
        
        /* 当正在生成时隐藏发送按钮，显示停止按钮 */
        .ai-chatbox-input.ai-generating .ai-send-btn {
          display: none;
        }
        
        .ai-chatbox-input.ai-generating .ai-stop-btn {
          display: flex;
        }
      `;
      document.head.appendChild(style);

      // 添加点击事件
      stopButton.addEventListener("click", stopGeneration);

      console.log("停止按钮已设置");
    }

    // 全局变量，用于追踪当前请求
    let currentRequestId = null;
    let isGenerating = false;

    // 修改停止生成函数
    function stopGeneration() {
      if (currentRequestId) {
        console.log("停止生成，请求ID:", currentRequestId);
        const requestIdToStop = currentRequestId;

        // 显示正在停止的提示
        const messages = document.querySelectorAll(".ai-message.assistant");
        if (messages.length > 0) {
          const lastMessage = messages[messages.length - 1];

          // 移除已有的停止提示（如果有）
          const existingStoppingNode = lastMessage.querySelector(
            ".ai-generation-stopping"
          );
          if (existingStoppingNode) {
            existingStoppingNode.remove();
          }

          lastMessage.innerHTML +=
            '<div class="ai-generation-stopping">[正在停止生成...]</div>';
        }

        // 保存请求ID，然后清除当前请求ID以防止重复点击
        const originalRequestId = currentRequestId;
        currentRequestId = null;

        // 立即更新UI状态，添加停止中样式
        const inputArea = document.querySelector(".ai-chatbox-input");
        inputArea.classList.add("ai-stopping");
        inputArea.classList.remove("ai-generating");

        // 通知后台脚本停止生成
        browser.runtime
          .sendMessage({
            type: "stopGeneration",
            requestId: requestIdToStop,
          })
          .then(() => {
            console.log("停止请求已发送成功:", requestIdToStop);
          })
          .catch((err) => {
            console.error("发送停止生成请求时出错:", err);
            currentRequestId = originalRequestId; // 恢复请求ID，允许再次尝试
          });

        // 添加消息监听器，确保能接收到停止确认消息
        const stopResponseListener = (message) => {
          if (
            (message.type === "alibabaApiStopped" ||
              message.type === "alibabaApiError") &&
            message.requestId === requestIdToStop
          ) {
            console.log("收到停止响应消息:", message.type);

            // 移除监听器
            browser.runtime.onMessage.removeListener(stopResponseListener);

            // 更新UI
            const inputArea = document.querySelector(".ai-chatbox-input");
            inputArea.classList.remove("ai-stopping");

            const messages = document.querySelectorAll(".ai-message.assistant");
            if (messages.length > 0) {
              const lastMessage = messages[messages.length - 1];

              // 移除"正在停止"提示
              const stoppingNode = lastMessage.querySelector(
                ".ai-generation-stopping"
              );
              if (stoppingNode) {
                stoppingNode.remove();
              }

              // 添加"已停止"提示
              if (!lastMessage.querySelector(".ai-generation-stopped")) {
                lastMessage.innerHTML +=
                  '<div class="ai-generation-stopped">[生成已停止]</div>';
              }
            }

            // 重置生成状态
            isGenerating = false;
          }
        };

        // 注册临时监听器来接收停止确认
        browser.runtime.onMessage.addListener(stopResponseListener);

        // 5秒后如果没有收到响应，也更新UI状态（以防消息丢失）
        setTimeout(() => {
          const stoppingNode = document.querySelector(
            ".ai-generation-stopping"
          );
          if (stoppingNode) {
            stoppingNode.remove();

            const lastMessage = stoppingNode.parentElement;
            if (
              lastMessage &&
              !lastMessage.querySelector(".ai-generation-stopped")
            ) {
              lastMessage.innerHTML +=
                '<div class="ai-generation-stopped">[生成已停止]</div>';
            }

            // 更新UI状态
            const inputArea = document.querySelector(".ai-chatbox-input");
            inputArea.classList.remove("ai-stopping");

            // 重置生成状态
            isGenerating = false;
          }
        }, 5000);
      } else {
        console.warn("没有正在进行的请求可以停止");
      }
    }

    // 在初始化UI时调用此函数
    function initUI() {
      setupStopButton();
      console.log("UI初始化完成");
    }

    // 确保initUI在main函数中调用
    // 最好在创建其他UI元素之后调用
    initUI();
  },
});
